package com.xsomnus.java_basic.juc;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 叶小夏
 * @since 2019-08-26 09:31
 *
 * // volatile不能保证线程安全，他的主要作用是
 * 1. 内存可见性
 * 2. 禁止指令重排
 */
public class VolatileTest {

    private static int counter = 0;

    private static ReentrantLock lock  = new ReentrantLock();

    public static class AddTread extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 100; i++) {
                    counter++;
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        ArrayList<AddTread> threads = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            AddTread addTread = new AddTread();
            threads.add(addTread);
        }


        threads.forEach(AddTread::start);


        Thread.sleep(5000);

        System.out.println(counter);
    }
}
